import logging as log

try:
    from info_config import db_pt_request_url

except ImportError as e:
    from info_config import db_pt_request_url

try:
    from urllib.parse import urlencode
    from urllib.request import Request, urlopen

except ImportError as e:
    from urllib.parse import urlencode
    from urllib.request import Request, urlopen


def message_send(queue, message):
    request_url = db_pt_request_url
    log.info(request_url)
    message = {'queue': queue, 'body': str(message)}

    request = Request(db_pt_request_url, urlencode(message).encode())
    body = urlopen(request).read().decode()
    log.info(body)
    return body


class RBInfo(object):
    def __init__(self, rbmq_exchange, rbmq_queue):
        self.rbmq_exchange = rbmq_exchange
        self.rbmq_queue = rbmq_queue
        self.publish_info = {}

    def publish_info_update(self, update_dict):
        try:
            self.publish_info = {**self.publish_info, **update_dict}
        except TypeError as e:
            log.exception(str(e))

    def backup_startup_publish(self):
        body = message_send(self.rbmq_queue, self.publish_info)
        return body
